package org.dftproject.gedcom.core;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.dftproject.genesis.data.IAttribute;
import org.dftproject.genesis.data.genealogy.Events;
import org.dftproject.genesis.data.genealogy.IRole;
import org.dftproject.genesis.data.genealogy.ISource;
import org.dftproject.genesis.data.genealogy.impl.EventImpl;
import org.dftproject.genesis.data.impl.AttributeImpl;

public class Event extends EventImpl {
	
	private final Line record;
	
	private boolean basicAttributesInit = false;
	
	public Event(Line record) {
		this.record = record;
	}
	
	@Override
	public Set<IAttribute> getAttributes() {
		if (!basicAttributesInit)
			initAttributes();
		return super.getAttributes();
	}
	
	@Override
	public Set<IAttribute> getAttributes(String name) {
		if (!basicAttributesInit)
			initAttributes();
		return super.getAttributes(name);
	}
	
	@Override
	public Set<IRole> getRoles() {
		if (!basicAttributesInit)
			initAttributes();
		return super.getRoles();
	}
	
	@Override
	public Set<IRole> getRoles(String type) {
		if (!basicAttributesInit)
			initAttributes();
		return super.getRoles(type);
	}
	
	@Override
	public Set<IRole> getRoles(String[] types) {
		if (!basicAttributesInit)
			initAttributes();
		return super.getRoles(types);
	}
	
	protected void initAttributes() {
		basicAttributesInit = true;
		
		if (record != null) {
			List<ISource> sources = new LinkedList<ISource>();
			for (Line source : record.getChildren("SOUR"))
				sources.add(new Source(source));
			
			for (Line line : record.getChildren()) {
				if ("DATE".equals(line.getTag())) {
					AttributeImpl attribute = new AttributeImpl(Events.instant, new Date(line));
					InternalUtils.addSources(attribute, sources);
					addAttribute(attribute);
				} else if ("PLAC".equals(line.getTag())) {
					AttributeImpl attribute = new AttributeImpl(Events.place, new Place(line));
					InternalUtils.addSources(attribute, sources);
					addAttribute(attribute);
				}
			}
		}
	}

}
